package com.mars.weixin.activemq.consumer;

import java.io.File;

import javax.activation.MimetypesFileTypeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mars.base.common.utils.file.cloud.UploadCloudStroe;
import com.mars.base.common.utils.file.cloud.UploadResult;
import com.mars.base.common.utils.http.HttpHelper;
import com.mars.base.common.utils.http.HttpResult;
import com.mars.boss.weixin.entity.WxMedia;
import com.mars.boss.weixin.service.WxMediaService;
import com.mars.component.mq.JmsQueueMessage;
import com.mars.weixin.service.ApiService;

/**
 * 微信异步消息处理
 * @author yhaoquan
 *
 */
@Component
public class WeixinMessageConsumer {
	private static Logger logger = LoggerFactory.getLogger(WeixinMessageConsumer.class);
	
	@Autowired
	private ApiService apiService ;
	
	@Autowired
	private WxMediaService wxMediaService ;
	
	@Autowired
	private UploadCloudStroe uploadCloudStroe ;
	
	@Autowired
	private JmsQueueMessage jmsQueueMessage ;
	
	@JmsListener(destination="weixin.media")
	public void saveMediaDownloadInfo(File file) {
		logger.info("收到MQ异步消息 ，队列名称[weixin.media]");
		try {
			WxMedia entity = new WxMedia() ;
			
			entity.setFileName(file.getName());
			entity.setFileLength(file.length()) ;
			entity.setContentType(new MimetypesFileTypeMap().getContentType(file));
			entity.setMediaType("image");
			
			//将本地文件上传到七牛云存储
			UploadResult result = this.uploadCloudStroe.uploadFile(file) ;
			entity.setViewUrl(result.getFileUrl());
			entity.setStoreDest("cloud");
			
			//上传到云存储服务器失败，则将文件转存到本地文件服务器
			if(!result.getStatus()) {
				logger.info("文件上传到云存储服务器发生错误，将转存到本地文件服务器");
				HttpResult httpResult = HttpHelper.executeUploadFile("http://attach.tukuan.com/cors/upload", file.getAbsolutePath()) ;
				
				JSONObject jsonObject = JSON.parseObject(httpResult.getContent()) ;
				JSONArray parseArray = JSON.parseArray(jsonObject.get("files").toString()) ;
				JSONObject fileinfo = parseArray.getJSONObject(0) ;
				
				entity.setStoreDest("local");
				entity.setViewUrl(fileinfo.getString("url"));
			}
			
			//文件信息持久化
			this.wxMediaService.insertSelective(entity) ;
			logger.info("文件数据持久化成功");
			
			
			logger.info("文件上传成功：{}", result);
		} catch (Exception e) {
			//发送异常异步消息
			this.jmsQueueMessage.send("app.exception", e.getMessage());
		}
	}
	
}
